<template>
    <van-nav-bar left-arrow title="订单结算" fixed @click-left="onBack" />

    <div style="height: 46px;"></div>

    <van-contact-card type="add" add-text="选择收货人" @click="onAdd(state.AddressInfo.id)"
        v-if="Object.keys(state.AddressInfo).length == 0" />

    <van-contact-card type="edit" :tel="state.AddressInfo.mobile" :name="state.AddressInfo.consignee" v-else
        @click="onEdit(state.AddressInfo.id)" />

    <!-- 选择的购物车的商品数据 -->
    <van-card v-for="item in state.CartList" :key="item.id" :num="item.pronum" :price="item.total"
        :title="item.product.name" :thumb="item.product.avatars_cdn[0]">
        <template #desc>
            <span>商品单价：￥{{ item.price }}</span>
        </template>
    </van-card>

    <!-- 订单备注 -->
    <van-cell-group inset style="border: 1px solid #ccc;">
        <van-field v-model="state.content" rows="2" autosize label="订单备注" type="textarea" maxlength="50"
            placeholder="请输入订单备注" show-word-limit />
    </van-cell-group>

    <van-submit-bar :price="state.total" button-text="结算" @submit="onSubmit" />
</template>
<script setup>
import { reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import apiList from '@/api'
import { useUserStore } from '@/store/user.js'
import { useProductStore } from '@/store/product.js'
import { showNotify } from 'vant'
import resJudge from '@/hooks/res.js'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const productStore = useProductStore()

const state = reactive({
    AddressInfo: {},
    CartList: [],
    content: '',
    total: parseFloat(route.query.total),
})

const onBack = () => {
    if (route.query.action == 'productInfo') {
        router.push({path:'/product/product/info',query:{proid:productStore.productInfo.product.id}})
    } else {
        router.push('/order/cart/index')
    }
}

onMounted(async () => {
    //用户更改了收获地址
    if (route.query.addrid) {
        let data = {
            id: route.query.addrid,
            busid: route.query.busid
        }
        let res = await apiList.AddressEditQuery(data)
        if (res.code == 1) {
            state.AddressInfo = res.data
        } else {
            showNotify({
                type: 'warning',
                message: '修改失败',
                duration: 1500,
            })
        }
    } else {
        //展示默认地址
        getAddressDefault()//获取默认地址
    }
    // console.log(Object.keys(productStore.productInfo).length);//0
    if (route.query.action == 'productInfo' && Object.keys(productStore.productInfo).length != 0) {
        let total = parseFloat(productStore.productInfo.product.price * productStore.productInfo.pronum).toFixed(2)
        let data = [
            {
                id: productStore.productInfo.product.id,
                price: productStore.productInfo.product.price,
                product: productStore.productInfo.product,
                proid: productStore.productInfo.product.id,
                pronum: productStore.productInfo.pronum,
                total,
            }
        ]
        state.CartList = data
        state.content = productStore.productInfo.content
        state.total = parseFloat(data[0].total * 100)
    } else {
        getConfirmData()//获取提交订单的商品
    }
})

async function getAddressDefault() {
    let result = await apiList.AddressDefault({ busid: userStore.userInfo.id })
    if (result.code === 1) {
        state.AddressInfo = result.data
    }
}
async function getConfirmData() {
    let cartids = route.query.cartids || ''

    let result = await apiList.CartConfirmData({ cartids })

    if (result.code === 0) {
        showNotify({
            type: 'warning',
            message: result.msg,
            duration: 1500,
            onClose: () => {
                router.go(-1)
            }
        })

        return false
    }

    state.CartList = result.data
}
function onEdit(addid) {
    if (route.query.action == 'productInfo') {
        router.push({ path: '/business/address/index', query: { addid,action: 'productInfo' } })
    } else {
        router.push({ path: '/business/address/index', query: { addid, action: 'order', cartids: route.query.cartids, total: parseFloat(route.query.total) } })
    }
}
function onAdd(addid) {
    router.push({ path: '/business/address/index', query: { addid, action: 'order', cartids: route.query.cartids, total: parseFloat(route.query.total) } })
}
async function onSubmit() {

    if (route.query.action == 'productInfo') {
        let data = {
            proid: productStore.productInfo.product.id,
            busid: userStore.userInfo.id,
            content: state.content,
            addrid: state.AddressInfo.id,
            pronum: productStore.productInfo.pronum,
            total: parseFloat(productStore.productInfo.product.price * productStore.productInfo.pronum).toFixed(2)
        }
        let result = await apiList.DirectSubmit(data)
        if (resJudge(result)) {
            if (route.query.action == 'productInfo') {
                productStore.$patch(state => {
                    state.productInfo = {}
                })
                localStorage.removeItem('productInfo')
            }
            router.push('/order/order/index')
        }
        return
    }
    // 获取购物车的id
    let cartids = route.query.cartids || ''

    let data = {
        cartids: cartids,
        busid: userStore.userInfo.id,
        content: state.content,
        addrid: state.AddressInfo.id
    }

    let result = await apiList.OrderSubmit(data)

    if (resJudge(result)) {
        router.push('/order/order/index')
    }
}

</script>
